package com.googlespeech.webapi.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.googlespeech.webapi.service.GoogleSpeech;

/**
 * Handles requests for the application home page.
 */
@Controller
@RequestMapping(value="/read")
public class ReadController {
	
	private static final Logger logger = LoggerFactory.getLogger(ReadController.class);
	
	@Autowired
	GoogleSpeech googleService;
	
	@RequestMapping(value = "/{text:.+}", method = RequestMethod.GET)
	public void get(@PathVariable String text, HttpServletResponse response) throws IOException {
		logger.info("Entrée dans controller Read en GET");
		response.setContentType("audio/mpeg");
		try{
			response.getOutputStream().write(googleService.getMp3FromText(text));
		}catch(IOException e){
			logger.error(e.toString());
		}
		
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public void post(@RequestParam("text") String text, HttpServletResponse response) throws IOException {
		logger.info("Entrée dans controller Read en POST");
		response.setContentType("audio/mpeg");
		response.getOutputStream().write(googleService.getMp3FromText(text));
	}
	
}
